package com.zengde.ai_sandbox.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Service
public class OssFileService {

    @Autowired
    private OSS ossClient;

    @Value("${oss.bucket-name}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.temp.pic-dir}")
    private String tempPicDir;

    @Value("${oss.temp.excel-dir}")
    private String tempExcelDir;

    @Value("${oss.product.pic-dir}")
    private String productPicDir;

    @Value("${oss.product.excel-dir}")
    private String productExcelDir;

    // 上传临时文件（30分钟有效期）
    public String uploadTempFile(MultipartFile file, int type) throws IOException {
        // 校验文件大小（2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过2MB");
        }        // 校验文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        
        if (type == 0) { // 图片
            if (!originalFilename.matches(".*\\.(png|jpg|jpeg)$")) {
                throw new IllegalArgumentException("图片仅支持PNG/JPG/JPEG格式");
            }
        } else if (type == 1) { // Excel
            if (!originalFilename.matches(".*\\.(xls|xlsx)$")) {
                throw new IllegalArgumentException("Excel仅支持xls/xlsx格式");
            }
        } else {
            throw new IllegalArgumentException("type参数错误（0:图片，1:Excel）");
        }

        // 生成临时路径
        String tempDir = type == 0 ? tempPicDir : tempExcelDir;
        String fileName = System.currentTimeMillis() + "_" + originalFilename;
        String objectName = tempDir + "/" + fileName;        // 设置文件元信息
        ObjectMetadata metadata = new ObjectMetadata();
        // 设置30分钟后过期
        Date expiration = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
        metadata.setExpirationTime(expiration);
        
        // 上传文件到OSS
        ossClient.putObject(bucketName, objectName, file.getInputStream(), metadata);

        return "http://" + bucketName + "." + endpoint + "/" + objectName;
    }

    // 移动临时文件到正式目录（永久有效）
    public String moveToProduct(String fileName, int type) {
        String tempDir = type == 0 ? tempPicDir : tempExcelDir;
        String productDir = type == 0 ? productPicDir : productExcelDir;
        String sourcePath = tempDir + "/" + fileName;
        String targetPath = productDir + "/" + fileName;        // 复制文件到正式目录
        ossClient.copyObject(bucketName, sourcePath, bucketName, targetPath);

        // 删除原临时文件
        ossClient.deleteObject(bucketName, sourcePath);

        // 生成正式URL
        return "http://" + bucketName + "." + endpoint + "/" + targetPath;
    }
}
